/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.sun.faces.lifecycle.Phase;
import ejb.common.DettaglioOrdineManagerLocal;
import ejb.common.DettaglioPrezzoManagerLocal;
import entity.DettaglioOrdine;
import entity.Ordine;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.context.FacesContext;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import utility.ExceptionThrower;
import utility.ResourceBundleLoader;

/**
 *
 * @author Valerio
 */
public class PDFCreator {
    @EJB
    private DettaglioOrdineManagerLocal dettaglioOrdineManager;
    @EJB
    private DettaglioPrezzoManagerLocal dettaglioPrezzoManager;
    private static Font titoloFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,
            Font.BOLD);
    private static Font testataFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
            Font.UNDERLINE);
    private static Font testoFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,
            Font.NORMAL);
    private static Font totaleFont = new Font(Font.FontFamily.TIMES_ROMAN, 16,
            Font.NORMAL, BaseColor.GREEN);

    public StreamedContent getRicuvutaPDF(Ordine o) {
        FacesContext fc=FacesContext.getCurrentInstance();
        ResourceBundle rb= ResourceBundleLoader.getResourceBundle(fc);
        try {
            return getRicevuta(o);
        } catch (DocumentException ex) {
            Logger.getLogger(PDFCreator.class.getName()).log(Level.SEVERE, null, ex);
            ExceptionThrower.throwMessageError(fc, rb, "ricevutaErrorM");
            return null;
        }
    }

    /**
     * Creates a new instance of PDFCreator
     */
    public PDFCreator() {
    }

    private StreamedContent getRicevuta(Ordine o) throws DocumentException {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Document pdf = new Document();
        PdfWriter writer = PdfWriter.getInstance(pdf, os);
        pdf.open();
        creaDocumento(pdf, o);
        pdf.close();
        DefaultStreamedContent sc = new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()));
        sc.setContentEncoding("application/pdf");
        sc.setContentType("application/pdf");
        sc.setName("Ricevuta n. " + o.getId());
        return sc;
    }

    private void creaDocumento(Document pdf, Ordine o) throws DocumentException {
        Long idNegozio = o.getNegozio().getId();
        //METADATA
        pdf.addAuthor("E-market");
        pdf.addCreator("E-Market");
        pdf.addCreationDate();
        pdf.addTitle("Ricevuta n. " + o.getId());
        Paragraph contenuto = new Paragraph();
        contenuto.add(new Paragraph(" "));
        //TITOLO
        contenuto.add(new Paragraph("E-market ricevuta ordine:", titoloFont));
        contenuto.add(new Paragraph(" "));
        //PRETABELLA
        contenuto.add(new Paragraph("Questi sono gli articoli presenti nel tuo ordine", testataFont));
        contenuto.add(new Paragraph("Negozio:" + o.getNegozio().getNome(), testataFont));
        contenuto.add(new Paragraph("Cliente:" + o.getCliente().getNome()+" "+o.getCliente().getCognome(), testataFont));
        contenuto.add(new Paragraph(" "));
        //TABELLA
        PdfPTable table = new PdfPTable(4);
        //header
        PdfPCell c1 = new PdfPCell(new Phrase("Codice a barre"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("Nome"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("Prezzo(€)"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("Quantita'"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
        table.setHeaderRows(1);
        List<DettaglioOrdine> dettOrdini=dettaglioOrdineManager.ottieniDaOrdine(o.getId());
        //contenuto
        for (DettaglioOrdine dettaglioOrdine : dettOrdini) {
            c1 = new PdfPCell(new Phrase(dettaglioOrdine.getProdotto().getCodiceBarre().toString()));
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c1);

            c1 = new PdfPCell(new Phrase(dettaglioOrdine.getProdotto().getNome()));
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c1);
            
            Float prezzo=dettaglioPrezzoManager.prezzoProdotto(idNegozio, dettaglioOrdine.getProdotto().getCodiceBarre());
            c1 = new PdfPCell(new Phrase(prezzo.toString().replace(".", ",")));
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c1);

            c1 = new PdfPCell(new Phrase(dettaglioOrdine.getQuantità().toString()));
            c1.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(c1);
        }
        //total
        if(!pdf.isOpen()){
            pdf.open();
        }
        contenuto.add(table);
        contenuto.add(new Paragraph(" "));
        contenuto.add(new Paragraph("Totale: "+o.getTotale().toString().replace(".",",")+"€", totaleFont));
        pdf.add(contenuto);
    }
}
